package com.songshuai.pangu.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.songshuai.pangu.api.component.CustMeetingComponent;
import com.songshuai.pangu.api.dto.pangu.*;
import com.songshuai.pangu.api.service.CustMeetingService;
import com.songshuai.webapi.baseapi.dto.feign.request.custminiprogram.AddMeetingReceiptReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.custminiprogram.MeetingDetailReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.custminiprogram.MeetingReceiptReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.custminiprogram.WxQRCodeReqDto;
import com.songshuai.webapi.baseapi.dto.feign.response.custminiprogram.*;
import com.songshuai.webapi.baseapi.dto.pangu.response.my.InvolvedActivityResDto;
import com.songshuai.webapi.baseapi.dto.pangu.response.my.SaleResDto;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.model.custminiprogram.*;
import com.songshuai.webapi.baseapi.pojo.QueryRes;
import com.songshuai.webapi.baseapi.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author:wbl
 * @Data:2019/3/30
 */
@Service
@Slf4j
public class CustMeetingServiceImpl implements CustMeetingService {

    @Autowired
    private CustMeetingComponent custMeetingComponent;

    //根据客户id获取会议列表
    @Override
    public List<MeetingListResDto> getMeetingListByUserId(String customId) {
        String response = custMeetingComponent.getMeetingListByUserId(customId);
        if (StringUtils.isNotBlank(response)){
            QueryRes<List<QueryMeetingListResDto>> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<List<QueryMeetingListResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                List<QueryMeetingListResDto> result = queryRes.getResult();
                if(result != null){
                    List<MeetingListResDto> resList =  result.stream().map(x -> {
                        return new MeetingListResDto() {{
                            setId(x.getId());
                            setCode(x.getCode());
                            setInviteNo(x.getInviteNo());
                            setTheme(x.getTheme());
                            setStarTime(x.getStarTime());
                            setEndTime(x.getEndTime());
                            setProvinceId(x.getProvinceId());
                            setProvince(x.getProvince());
                            setCityId(x.getCityId());
                            setCity(x.getCity());
                            setAreaId(x.getAreaId());
                            setArea(x.getArea());
                            setAddress(x.getAddress());
                            setChargeManId(x.getChargeManId());
                            setChargeManName(x.getChargeManName());
                            setChargeManTel(x.getChargeManTel());
                            setLng(x.getLng());
                            setLat(x.getLat());
                            setIsReceipt(x.getIsReceipt());
                            setIsBegin(x.getIsSign());
                            setClueGuid(x.getClueGuid());
                            setCustomGuid(x.getCustomGuid());
                            setMeetingIsNeedMeet(x.getMeetingIsNeedMeet());
                        }};
                    }).collect(Collectors.toList());
                    List<MeetingListResDto> resDtoList = new ArrayList<>();
                    for(MeetingListResDto resDto : resList){
                        Date endDate = DateUtil.ChangeStringToDate(resDto.getEndTime(),DateUtil.dateFormat1);
                        Date nowDate = new Date();
                        if(!endDate.before(nowDate)){//未来的，正在进行中的
                            resDtoList.add(resDto);
                        }
                    }
                    return resDtoList;
                }
                return new ArrayList<>();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }

    //根据邀约编号获取回执单
    @Override
    public MeetingReceiptResDto getMeetingReceipt(MeetingReceiptReqDto parm) {
        String response = custMeetingComponent.queryReceipt(parm);
        if (StringUtils.isNotBlank(response)){
            QueryRes<QueryReceiptByInviteNoResDto> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<QueryReceiptByInviteNoResDto>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                QueryReceiptByInviteNoResDto result = queryRes.getResult();
                if(result != null) {
                    MeetingReceiptResDto resDto = new MeetingReceiptResDto() {{
                        setId(result.getId());
                        setReceiptNo(result.getReceipt_No());
                        setMeetingNo(result.getMeeting_No());
                        setCustomGuid(result.getCustomGuid());
                        setCustomName(result.getCustomName());
                        setCustomTel(result.getCustomTel());
                        setClueGuid(result.getClueGuid());
                        setInviteNo(result.getInvite_no());
                        setCompanionNum(result.getCompanionNum());
                        setIsNeedRoom(result.getIsNeedRoom());
                        setTenants(result.getTenants());
                        setRoomStyle(result.getRoomStyle());
                        setRoomStyleName(result.getRoomStyleName());
                        setTripMode(result.getTripMode());
                        setTripModeName(result.getTripModeName());
                        setFlightOrTrainNum(result.getFlightOrTrainNum());
                        setIsFullAttend(result.getIsFullAttend());
                        setRoomCnt(result.getRoomCnt());
                        setIsNeedMeet(result.getIsNeedMeet());
                        setStation(result.getStation());
                        setStationName(result.getStationName());
                        setArriveTime(result.getArriveTime());
                        setBack(result.getBack());
                    }};
                    if(result.getPicList() != null){
                        resDto.setPicList(result.getPicList().stream().map(x -> {
                            return new MeetingPicture(){{
                                setPicName(x.getName());
                                setPicAddress(x.getAddress());
                                setPicSort(x.getPicSort());
                            }};
                        }).collect(Collectors.toList()));
                    }
                    return resDto;
                }
                return new MeetingReceiptResDto();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }

    //根据邀约编号获取会议详情
    @Override
    public MeetingDetailResDto getMeetingDetail(MeetingDetailReqDto parm) {
        String response = custMeetingComponent.getMeetingDetail(parm);
        if (StringUtils.isNotBlank(response)){
            QueryRes<QueryMeetingDetailResDto> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<QueryMeetingDetailResDto>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                QueryMeetingDetailResDto result = queryRes.getResult();
                if(result != null){
                    MeetingDetailResDto resDto = new MeetingDetailResDto() {{
                        setId(result.getId());
                        setCode(result.getCode());
                        setInviteNo(result.getInviteNo());
                        setTheme(result.getTheme());
                        setStarTime(result.getStarTime());
                        setEndTime(result.getEndTime());
                        setProvinceId(result.getProvinceId());
                        setProvince(result.getProvince());
                        setCityId(result.getCityId());
                        setCity(result.getCity());
                        setAreaId(result.getAreaId());
                        setArea(result.getArea());
                        setAddress(result.getAddress());
                        setChargeManId(result.getChargeManId());
                        setChargeManName(result.getChargeManName());
                        setChargeManTel(result.getChargeManTel());
                        setLng(result.getLng());
                        setLat(result.getLat());
                        setIsReceipt(result.getIsReceipt());
                        setIsSign(result.getIsSign());
                        setIsCurrSign(result.getIsCurrSign());
                        setAssignName(result.getAssignName());
                        setAssignTel(result.getAssignTel());
                        setCustomerName(result.getCustomerName());
                        setCustomerTel(result.getCustomerTel());
                        setClueGuid(result.getClueGuid());
                        setCustomGuid(result.getCustomGuid());
                    }};
                    if(result.getMeetingHotel() !=  null){
                        resDto.setMeetingHotel(new MeetingHotel(){{
                            setHotelId(result.getMeetingHotel().getHotelId());
                            setHotelName(result.getMeetingHotel().getHotelName());
                            setHotelAddress(result.getMeetingHotel().getHotelAddress());
                            setIntroduce(result.getMeetingHotel().getIntroduce());
                            setLng(result.getMeetingHotel().getLng());
                            setLat(result.getMeetingHotel().getLat());
                            setPicAddress(result.getMeetingHotel().getPicAddress());
                        }});
                    }
                    if(result.getMeetingStation() != null){
                        resDto.setMeetingStation(new MeetingStation(){{
                            setStationId(result.getMeetingStation().getStationId());
                            setContactName(result.getMeetingStation().getContactName());
                            setContactNo(result.getMeetingStation().getContactNo());
                            setRemark(result.getMeetingStation().getRemark());
                        }});
                    }
                    if(result.getScheduleList() != null){
                        List<MeetingSchedule> meetingScheduleList = result.getScheduleList().stream().map(x -> {
                            return new MeetingSchedule(){{
                                setId(x.getId());
                                setDate(x.getDate());
                                setStarTime(x.getStarTime());
                                setEndTime(x.getEndTime());
                                setDuration(x.getDuration());
                                setMatter(x.getMatter());
                                setContent(x.getContent());
                                setChargeMan(x.getChargeMan());
                                setChargeManId(x.getChargeManId());

                            }};
                        }).collect(Collectors.toList());

                        List<String> dateList = meetingScheduleList.stream().map(x -> x.getDate()).collect(Collectors.toList());
                        Set<String> dateSet = new HashSet<>(dateList);
                        List<MeetingScheduleDate> scheduleDateList = new ArrayList<>();
                        for(String date : dateSet){
                            MeetingScheduleDate scheduleDate = new MeetingScheduleDate();
                            scheduleDate.setDate(date);
                            List<MeetingSchedule> scheduleList = new ArrayList<>();
                            for(MeetingSchedule meetingSchedule : meetingScheduleList){
                                if(date.equals(meetingSchedule.getDate())){
                                    scheduleList.add(meetingSchedule);
                                }
                            }
                            scheduleDate.setScheduleList(scheduleList);
                            scheduleDateList.add(scheduleDate);
                        }
                        resDto.setScheduleDateList(scheduleDateList);
                    }
                    return resDto;
                }
                return new MeetingDetailResDto();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }

    //根据会议编号获取邀约模板
    @Override
    public List<InvitationTemplateResDto> getInvitationTemplateByCode(String meetingCode) {
        String response = custMeetingComponent.getInvitationTemplateByCode(meetingCode);
        if (StringUtils.isNotBlank(response)){
            QueryRes<List<QueryMeetingInviteResDto>> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<List<QueryMeetingInviteResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                List<QueryMeetingInviteResDto> result = queryRes.getResult();
                if(result != null) {
                    return result.stream().map(x -> {
                        return new InvitationTemplateResDto(){{
                            setMeetingCode(x.getMain_Key());
                            setPicName(x.getPicName());
                            setPicAddress(x.getPicAddress());
                            setPicSort(x.getPicSort());
                        }};
                    }).collect(Collectors.toList());
                }
                return new ArrayList<>();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }

    //根据线索id和会议编号获取签到码
    @Override
    public WxQRCodeResDto getWxQRCode(WxQRCodeReqDto parm) {
        String response = custMeetingComponent.getWxQRCode(parm);
        if (StringUtils.isNotBlank(response)) {
            QueryRes<QueryWxQRCodeResDto> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<QueryWxQRCodeResDto>>() {
            });
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()) {
                QueryWxQRCodeResDto result = queryRes.getResult();
                if (result != null) {
                    return new WxQRCodeResDto() {{
                        setToken(result.getToken());
                        setClueguid(result.getClueguid());
                        setMeetingno(result.getMeetingno());
                        setTimestamp(result.getTimestamp());
                    }};
                }
                return new WxQRCodeResDto();
            } else {
                throw new BusinessException(queryRes.getInfo(), ResultStatus.FAILOfficial);
            }
        }
        return null;
    }
    @Override
    public SaleResDto getMySale(String customerId) {
        String response = custMeetingComponent.getMySale(customerId);
        if(StringUtils.isNotBlank(response)){
            QueryRes<SaleResDto> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<SaleResDto>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                SaleResDto sale = queryRes.getResult();
                sale.setSaleWechatNo("");
                return sale;
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }

    //新增回执单
    @Override
    public AddMeetingReceiptResDto addMeetingReceipt(AddMeetingReceiptReqDto parm) {
        String response = custMeetingComponent.addMeetingReceipt(parm);
        log.info("新增回执单，盘古返回结果："+response);
        if (StringUtils.isNotBlank(response)){
            QueryRes<AddReceiptResDto> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<AddReceiptResDto>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                AddReceiptResDto result = queryRes.getResult();
                if(result != null) {
                    return new AddMeetingReceiptResDto(){{
                        setToken(result.getToken());
                        setClueguid(result.getClueguid());
                        setMeetingno(result.getMeetingno());
                        setTimestamp(result.getTimestamp());
                    }};
                }
                return new AddMeetingReceiptResDto();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }

    //根据会议编号获取车站信息
    @Override
    public List<StationResDto> getAreaStations(String meetingCode) {
        String response = custMeetingComponent.getAreaStations(meetingCode);
        if (StringUtils.isNotBlank(response)){
            QueryRes<List<QueryStationResDto>> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<List<QueryStationResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                List<QueryStationResDto> result = queryRes.getResult();
                if(result != null) {
                    return result.stream().map(x -> {
                        return new StationResDto(){{
                            setId(x.getStationId());
                            setStationName(x.getStationName());
                            setSort(x.getSort());
                        }};
                    }).collect(Collectors.toList());
                }
                return new ArrayList<>();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }

    @Override
    public Integer queryHistoryActivityCount(String customerId) {
        Integer count = 0;
        String response = custMeetingComponent.queryHistoryActivityList(customerId);
        if(StringUtils.isNotBlank(response)){
            QueryRes<List<InvolvedActivityResDto>> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<List<InvolvedActivityResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                List<InvolvedActivityResDto> result = queryRes.getResult();
                if(!CollectionUtils.isEmpty(result)){
                    count = result.size();
                }
            }
        }
        return count;
    }

    @Override
    public List<InvolvedActivityResDto> queryHistoryActivityList(String customerId) {
        String response = custMeetingComponent.queryHistoryActivityList(customerId);
        if(StringUtils.isNotBlank(response)){
            QueryRes<List<InvolvedActivityResDto>> queryRes = JSON.parseObject(response, new TypeReference<QueryRes<List<InvolvedActivityResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                List<InvolvedActivityResDto> result = queryRes.getResult();
                if(CollectionUtils.isEmpty(result)) {
                    result = new ArrayList<>();
                }
                return result;
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }
}
